package com.yanqu.road.dao.impl.player;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.config.manor.ManorWeather;
import com.yanqu.road.entity.manor.UserManorData;

import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2021/5/19 11:17
 */
public class UserManorDataDaoImpl extends TempDataObjectDao<UserManorData> {
    public static String insertSql = "insert into t_u_manor_data(userId,prosperousValue,farmLandUnLock,eventId,isGetReward,refreshTime,reward,rankActivityDataMap) values(?,?,?,?,?,?,?,?)";
    @Override
    protected boolean addData(UserManorData data) {
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getProsperousValue()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getFarmLandUnLock()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getEventId()));
        para.put(i++, new DbParameter(Types.BOOLEAN, data.isGetReward()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getRefreshTime()));
        para.put(i++, new DbParameter(Types.VARCHAR, data.getReward()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSONObject.toJSONString(data.getRankActivityDataMap())));

        return getDb().executeNoneQuery(insertSql, para) > 0;
    }

    public static String updateSql = "update t_u_manor_data set prosperousValue=?,farmLandUnLock=?,eventId=?,isGetReward=?,refreshTime=?,reward=?,rankActivityDataMap=? where userId=?";
    @Override
    protected boolean updateData(UserManorData data) {
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getProsperousValue()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getFarmLandUnLock()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getEventId()));
        para.put(i++, new DbParameter(Types.BOOLEAN, data.isGetReward()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getRefreshTime()));
        para.put(i++, new DbParameter(Types.VARCHAR, data.getReward()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSONObject.toJSONString(data.getRankActivityDataMap())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        return getDb().executeNoneQuery(updateSql, para) > 0;
    }

    @Override
    protected UserManorData parseData(ResultSet rs) throws SQLException {
        UserManorData userManorData = new UserManorData();
        userManorData.setUserId(rs.getLong("userId"));
        userManorData.setProsperousValue(rs.getLong("prosperousValue"));
        userManorData.setFarmLandUnLock(rs.getInt("farmLandUnLock"));
        userManorData.setEventId(rs.getInt("eventId"));
        userManorData.setGetReward(rs.getBoolean("isGetReward"));
        userManorData.setRefreshTime(rs.getLong("refreshTime"));
        userManorData.setReward(rs.getString("reward"));
        String rsString = rs.getString("rankActivityDataMap");
        if (rsString == null || rsString.isEmpty()) {
            userManorData.setRankActivityDataMap(new ConcurrentHashMap<>());
        } else {
            userManorData.setRankActivityDataMap(JSONObject.parseObject(rsString, new TypeReference<Map<Integer, Long>>() {}));
        }
        return userManorData;
    }

    public static String getManorDataSql = "select * from t_u_manor_data where userId=?";

    public UserManorData getUserManorData(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(getManorDataSql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public boolean insertManorWeather(List<ManorWeather> list) {
    String sql = "INSERT INTO t_u_manor_weather(weather,endTime) VALUES(?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (ManorWeather data : list) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.INTEGER, data.getWeather()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getEndTime()));
                mapList.add(para);
            }
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    public static String getWeatherSql = "select * from t_u_manor_weather order by endTime desc limit 2";
    public List<ManorWeather> getManorWeather() {
        ResultSet rs = null;
        CallableStatement call = null;
        List<ManorWeather> manorWeatherList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(getWeatherSql);
            rs = call.executeQuery();
            while (rs.next()) {
                ManorWeather manorWeather = new ManorWeather();
                manorWeather.setWeather(rs.getInt("weather"));
                manorWeather.setEndTime(rs.getLong("endTime"));
                manorWeatherList.add(manorWeather);
            }
            Collections.reverse(manorWeatherList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return manorWeatherList;
    }
}
